package com.monitor.app_monitor.config;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.monitor.app_monitor.entity.*;
import com.monitor.app_monitor.entity.mapper.RealTimeAlarmClickhouseMapper;
import com.monitor.app_monitor.entity.mapper.RealTimeAlarmMapper;
import com.monitor.app_monitor.entity.mapper.ResUnifClickhouseMapper;
import com.monitor.app_monitor.mapper.CellectInfoMapper;
import com.monitor.app_monitor.mapper.EmsInfoMapper;
import com.monitor.app_monitor.mapper.ServiceListMapper;
import com.monitor.app_monitor.mapper.TableListMapper;
import com.monitor.app_monitor.service.quartz.utils.ExecuteScript;
import com.monitor.app_monitor.service.quartz.utils.RgEmsInfo;
import com.monitor.app_monitor.service.quartz.utils.RgExecuteScript;
import com.monitor.app_monitor.service.quartz.utils.RgScriptExecResult;
import io.micrometer.core.instrument.ImmutableTag;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tag;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

@Data
@Configuration //1.主要用于标记配置类，兼备Component的效果。
@Slf4j
@Component
@EnableScheduling   // 2.开启定时任务
public class LoadMapConfiguration {

    @Autowired
    MeterRegistry registry;

    @Autowired
    ServiceListMapper serviceListMapper;

    @Autowired
    RealTimeAlarmMapper realTimeAlarmMapper;

    @Autowired
    RealTimeAlarmClickhouseMapper realTimeAlarmClickhouseMapper;

    @Resource
    private ClickHouseConfig clickHouseConfig;

    @Autowired
    TableListMapper tableListMapper;

    @Autowired
    EmsInfoMapper emsInfoMapper;

    @Autowired
    CellectInfoMapper cellectInfoMapper;

    @Autowired
    ResUnifClickhouseMapper resUnifClickhouseMapper;

    @Resource
    private RgExecuteScript rgExecuteScript;

    @Resource
    private ExecuteScript executeScript;

    @Value("${rgfileinfo}")
    private String rgfileinfo;

    @Resource
    @Qualifier("getRgInfo")
    private Map<String,String> getRgInfo;

    @Resource
    @Qualifier("dataAnalysisThreadPool")
    private ThreadPoolExecutor threadPoolExecutor;

    @Resource
    @Qualifier("spcThreadPool")
    private ThreadPoolExecutor spcThreadPool;

    public static void mapCopy(Map paramsMap, Map resultMap) {
        if (resultMap == null) resultMap = new HashMap();
        if (paramsMap == null) return;

        Iterator it = paramsMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            Object key = entry.getKey();
            resultMap.put(key, paramsMap.get(key) != null ? paramsMap.get(key) : "");

        }
    }

    //波分复用段统计map
    @Bean
    public Map<String,AtomicInteger> TrsSegInfo (){
        //
        Map<String,AtomicInteger> TrsSegInfoNo = new ConcurrentHashMap<>();

        return TrsSegInfoNo;
    }

    //初始化PmNceS监控map
    @Bean
    public Map<String,AtomicInteger> PmNceS (){
        //aaa
        Map<String,AtomicInteger> mapFileNb = new ConcurrentHashMap<>();

        try {
            Integer rgEmsInfos = executeScript.executePmNceSScript();
            log.info("查询当前文件夹：{}",rgEmsInfos);
            List<Tag> tags = new ArrayList<>();

            tags.add(new ImmutableTag("resType","PM-NCE-S"));

            AtomicInteger filenbint = registry.gauge("pm_nce_s", tags, new AtomicInteger(rgEmsInfos));

            mapFileNb.put("pm_nce_s",filenbint);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return mapFileNb;
    }

    //初始化二干文件大小监控map
//    @Bean
//    public Map<String,Map<String,AtomicInteger>> RgEmsMap (){
//
//        Map<String,Map<String,AtomicInteger>> bigmap = new ConcurrentHashMap<>();
//        Map<String,AtomicInteger> mapFileSize = new ConcurrentHashMap<>();
//        Map<String,AtomicInteger> mapFileNb = new ConcurrentHashMap<>();
//
//
//        try {
//            RgEmsInfo rgEmsInfos = rgExecuteScript.executeScript("/home/deployer/bin/RGDATAPRSS.py");
//
//            for (RgScriptExecResult rgEmsInfo : rgEmsInfos.getData()) {
//
//                this.spcThreadPool.submit(() -> {
//
//                    Integer fileNb = 0;
//                    Integer fileSize = 0;
//
//                    try {
//
//                        List<Tag> tags = new ArrayList<>();
//
//                        tags.add(new ImmutableTag("emsIp",rgEmsInfo.getEmsIp()));
//                        tags.add(new ImmutableTag("emsName",rgEmsInfo.getEmsName()));
//                        tags.add(new ImmutableTag("fileInfo",rgEmsInfo.getFileInfo()));
//                        tags.add(new ImmutableTag("fileName",rgEmsInfo.getFileName()));
//                        tags.add(new ImmutableTag("networForm",rgEmsInfo.getNetworForm()));
//                        tags.add(new ImmutableTag("nowData",rgEmsInfo.getNowData()));
//                        tags.add(new ImmutableTag("owner",rgEmsInfo.getOwner()));
//                        tags.add(new ImmutableTag("province_code",getRgInfo.get(rgEmsInfo.getProvince())));
//                        tags.add(new ImmutableTag("province",rgEmsInfo.getProvince()));
//                        tags.add(new ImmutableTag("resName",rgEmsInfo.getResName()));
//                        tags.add(new ImmutableTag("resType",rgEmsInfo.getResType()));
//
//                        AtomicInteger filenbint = registry.gauge("file_nb_rg", tags, new AtomicInteger(fileNb));
//                        AtomicInteger filesizeint = registry.gauge("file_size_rg", tags, new AtomicInteger(fileSize));
//
//                        mapFileNb.put(rgEmsInfo.getNowData()+rgEmsInfo.getFileInfo()+rgEmsInfo.getResName()+rgEmsInfo.getFileName(),filenbint);
//                        mapFileSize.put(rgEmsInfo.getNowData()+rgEmsInfo.getFileInfo()+rgEmsInfo.getResName()+rgEmsInfo.getFileName(),filesizeint);
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                });
//
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        bigmap.put("filesize",mapFileSize);
//        bigmap.put("filenb",mapFileNb);
//        return bigmap;
//    }


    @Bean
    public static Map<String,AtomicLong> pmFileSizeMap (){
        Map<String,AtomicLong> map = new HashMap<>();

//        try {
//            PmEmsInfo pmEmsInfos = executeScript.executePmScript("/home/deployer/bin/PmFileInfo.py");
//
//            Map<String, String> emsMap = CircuitMap.emsMap;
//            pmEmsInfos.getData().forEach(pmEmsInfo -> {
//                List<Tag> tags = new ArrayList<>();
//                tags.add(new ImmutableTag("emsName",pmEmsInfo.getFileName()));
//                tags.add(new ImmutableTag("fileName",pmEmsInfo.getEmsName()));
//                tags.add(new ImmutableTag("emsIp",emsMap.get(pmEmsInfo.getFileName())));
//                AtomicLong list = registry.gauge("pm_filesize", tags, new AtomicLong(0L));
//                map.put(pmEmsInfo.getFileName(),list);
//            });
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        return map;
    }


    @Bean
    public static Map<String, AtomicLong> pmFileNoMap (){
        Map<String,AtomicLong> map = new HashMap<>();

//        try {
//            PmEmsInfo pmEmsInfos = executeScript.executePmScript("/home/deployer/bin/PmFileInfo.py");
//
//            Map<String, String> emsMap = CircuitMap.emsMap;
//            pmEmsInfos.getData().forEach(pmEmsInfo -> {
//                List<Tag> tags = new ArrayList<>();
//                tags.add(new ImmutableTag("emsName",pmEmsInfo.getFileName()));
//                tags.add(new ImmutableTag("fileName",pmEmsInfo.getEmsName()));
//                tags.add(new ImmutableTag("emsIp",emsMap.get(pmEmsInfo.getFileName())));
//                AtomicLong list = registry.gauge("pm_file_no", tags, new AtomicLong(0));
//                map.put(pmEmsInfo.getFileName(),list);
//            });
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        return map;
    }

    @Bean
    public Map<String,AtomicInteger> appsMap (){
        Map<String,AtomicInteger> map = new HashMap<>();
        ServiceList serviceList = new ServiceList();
        QueryWrapper<ServiceList> queryWrapper = new QueryWrapper<>(serviceList) ;

        List<ServiceList> serviceLists = serviceListMapper.selectList(queryWrapper);

        serviceLists.forEach(app -> {
            List<Tag> tags = new ArrayList<>();
            tags.add(new ImmutableTag("host",app.getHost()));
            tags.add(new ImmutableTag("owner",app.getOwner()));
            tags.add(new ImmutableTag("emsName",app.getEmsName()));
            tags.add(new ImmutableTag("networkForm",app.getNetworkForm()));
            tags.add(new ImmutableTag("emsIp",app.getEmsIp()));
            tags.add(new ImmutableTag("gitAdds",app.getGitAdds()));
            tags.add(new ImmutableTag("jarName",app.getJarName()));
            tags.add(new ImmutableTag("env",app.getEnv()));
            tags.add(new ImmutableTag("port",String.valueOf(app.getPort())));
            tags.add(new ImmutableTag("developer",app.getDeveloper()));
            tags.add(new ImmutableTag("appDescribe",app.getAppDescribe()));
            tags.add(new ImmutableTag("note",app.getNote()));
            tags.add(new ImmutableTag("type",app.getType()));
            AtomicInteger list = registry.gauge("apps_status", tags, new AtomicInteger(0));
            map.put("appid-"+app.getId(),list);
        });
        return map;
    }

    @Bean
    public Map<String,AtomicInteger> cellectMap (){
        Map<String,AtomicInteger> map = new HashMap<>();
        List<CellectInfo> cellectInfos = cellectInfoMapper.selectList(new QueryWrapper<>(new CellectInfo()));

        cellectInfos.forEach(cellectInfo -> {
            List<Tag> tags = new ArrayList<>();
            tags.add(new ImmutableTag("emsName",cellectInfo.getEmsName()));
            tags.add(new ImmutableTag("resType",cellectInfo.getResType()));
            tags.add(new ImmutableTag("developer",cellectInfo.getDeveloper()));
            tags.add(new ImmutableTag("checkTime",cellectInfo.getCellectTime()));
            AtomicInteger list = registry.gauge("cellect_status", tags, new AtomicInteger(999999));
            map.put(cellectInfo.getEmsName()+cellectInfo.getResType(),list);
        });
        return map;
    }

    @Bean
    public Map<String,AtomicInteger> cellectfileSizeMap (){
        Map<String,AtomicInteger> map = new HashMap<>();
        List<CellectInfo> cellectInfos = cellectInfoMapper.selectList(new QueryWrapper<>(new CellectInfo()));

        cellectInfos.forEach(cellectInfo -> {
            List<Tag> tags = new ArrayList<>();
            tags.add(new ImmutableTag("emsName",cellectInfo.getEmsName()));
            tags.add(new ImmutableTag("resType",cellectInfo.getResType()));
            tags.add(new ImmutableTag("developer",cellectInfo.getDeveloper()));
            AtomicInteger list = registry.gauge("cellect_filesize", tags, new AtomicInteger(0));
            map.put(cellectInfo.getEmsName()+cellectInfo.getResType(),list);
        });
        return map;
    }

    @Bean
    public Map<String,AtomicInteger> cellectfileNbMap (){
        Map<String,AtomicInteger> map = new ConcurrentHashMap<>();
        List<CellectInfo> cellectInfos = cellectInfoMapper.selectList(new QueryWrapper<>(new CellectInfo()));

        cellectInfos.forEach(cellectInfo -> {
            List<Tag> tags = new ArrayList<>();
            tags.add(new ImmutableTag("emsName",cellectInfo.getEmsName()));
            tags.add(new ImmutableTag("resType",cellectInfo.getResType()));
            tags.add(new ImmutableTag("developer",cellectInfo.getDeveloper()));
            AtomicInteger list = registry.gauge("cellect_filenumber", tags, new AtomicInteger(0));
            map.put(cellectInfo.getEmsName()+cellectInfo.getResType(),list);
        });
        return map;
    }

    @Bean
    public Map<String,AtomicInteger> realTimeAlarmMap (){
        Map<String,AtomicInteger> map = new HashMap<>();

        Date date = new Date();
        String strDateFormat = "yyyy-MM-dd";
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
        String nowData = sdf.format(date);
        List<RealTimeAlarmDo> realTimeAlarms = realTimeAlarmMapper.findAll(nowData);
        realTimeAlarms.forEach(realTimeAlarm -> {
            List<Tag> tags = new ArrayList<>();
            tags.add(new ImmutableTag("emsName",realTimeAlarm.getEmsName()));
            tags.add(new ImmutableTag("emsIp",realTimeAlarm.getEmsIp()));
            tags.add(new ImmutableTag("Data",nowData));
            AtomicInteger list = registry.gauge("clarm_mysql", tags, new AtomicInteger(realTimeAlarm.getEmsNb()));
            map.put(realTimeAlarm.getEmsName()+realTimeAlarm.getEmsIp()+nowData,list);
        });
        return map;
    }

    @Bean
    public Map<String,AtomicInteger> realTimeAlarmClickMap (){
        Map<String,AtomicInteger> map = new HashMap<>();

        Date date = new Date();
        String strDateFormat = "yyyy-MM-dd";
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
        String nowData = sdf.format(date);
        List<RealTimeAlarmDo> realTimeAlarms = null;
        try {
            realTimeAlarms = realTimeAlarmClickhouseMapper.findAllClick(nowData);
        } catch (Exception e) {
            log.error(e.toString());
        }

        realTimeAlarms.forEach(realTimeAlarm -> {
            List<Tag> tags = new ArrayList<>();
            tags.add(new ImmutableTag("emsName",realTimeAlarm.getEmsName()));
            tags.add(new ImmutableTag("emsIp",realTimeAlarm.getEmsIp()));
            tags.add(new ImmutableTag("Data",nowData));
            AtomicInteger list = registry.gauge("clarm_clickhouse", tags, new AtomicInteger(realTimeAlarm.getEmsNb()));
            map.put(realTimeAlarm.getEmsName()+realTimeAlarm.getEmsIp()+nowData,list);
        });
        return map;
    }



    @Bean
    public Map<String,AtomicInteger> dataKey (){
        //设置7天的时间查询
        Map<String,AtomicInteger> map = new HashMap<>();
        for (int i = 0; i < 7; i++) {
            Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
            ca.setTime(new Date());//月份是从0开始的，所以11表示12月
            ca.add(Calendar.DATE, -i); //月份减1
            Date lastMonth = ca.getTime(); //结果
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            String dataKey = sf.format(lastMonth);


            List<Tag> tags = new ArrayList<>();
            tags.add(new ImmutableTag("dataKey",dataKey));

            AtomicInteger list = registry.gauge("DataInfo", tags, new AtomicInteger(0));
            map.put(dataKey,list);
        }
        return map;
    }


    @Bean
    public Map<String,AtomicInteger> dataKey2 (){
        //设置7天的时间查询
        Map<String,AtomicInteger> map = new HashMap<>();
        for (int i = 0; i < 7; i++) {
            Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
            ca.setTime(new Date());//月份是从0开始的，所以11表示12月
            ca.add(Calendar.DATE, -i); //月份减1
            Date lastMonth = ca.getTime(); //结果
            SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
            String dataKey = sf.format(lastMonth);


            List<Tag> tags = new ArrayList<>();
            tags.add(new ImmutableTag("dataKey",dataKey));

            AtomicInteger list = registry.gauge("DataInfo2", tags, new AtomicInteger(0));
            map.put(dataKey,list);
        }
        return map;
    }


    @Bean
    public Map<String,AtomicInteger> tableByEmsIpMap (){
        Map<String,AtomicInteger> map = new HashMap<>();

        try {
            List<EmsInfo> emsInfos = emsInfoMapper.selectList(new QueryWrapper<>(new EmsInfo()));
            List<TableList> tableLists = tableListMapper.selectList(new LambdaQueryWrapper<TableList>()
                    .eq(TableList::getTrsType,"资源")
                    .or()
                    .eq(TableList::getTrsType,"拼接结果"));
            tableLists.forEach(tableList -> {
                emsInfos.forEach( emsInfo -> {

                    Integer allClick = 0;
     //                       resUnifClickhouseMapper.findAllClick(tableList.getTableName(), emsInfo.getEmsIp());

                    List<Tag> tags = new ArrayList<>();
                    tags.add(new ImmutableTag("tableName",tableList.getTableName()));
                    tags.add(new ImmutableTag("trsType",tableList.getTrsType()));
                    tags.add(new ImmutableTag("tableDescribe",tableList.getTableDescribe()));
                    tags.add(new ImmutableTag("emsIp",emsInfo.getEmsIp()));
                    tags.add(new ImmutableTag("emsName",emsInfo.getEmsName()));
                    AtomicInteger list = registry.gauge("table_status_by_emsip", tags, new AtomicInteger(allClick));
                    map.put(tableList.getTrsDatabase()+"--"+tableList.getTableName()+emsInfo.getEmsIp(),list);
                });
            });
        }catch (Exception e) {
            log.error(e.toString());
        }

        return map;
    }

}
